package com.itany.study.service.impl;

import com.itany.study.constant.UserStatusConstant;
import com.itany.study.dao.UserDao;
import com.itany.study.entity.User;
import com.itany.study.exception.LoginException;
import com.itany.study.exception.UsernameExistsException;
import com.itany.study.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


/**
 * Author：汤小洋
 * Date：2022-11-29 9:52
 * Description：<描述>
 */
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public User login(String username,String password) throws LoginException {
        User user = userDao.selectByUsername(username);
        if(user == null){
            throw new LoginException("用户名不存在！");
        }else if(! user.getPassword().equals(password)){
            throw new LoginException("密码不正确！");
        }else if(user.getStatus() != UserStatusConstant.ENABLE){
            throw new LoginException("用户被禁用！");
        }
        return user;
    }

    @Override
    public void register(User user) throws UsernameExistsException {
        // 判断用户名是否被占用
        User u = userDao.selectByUsername(user.getUsername());
        if (u !=null ){
            throw new UsernameExistsException("用户名已存在！");
        }

        // 插入数据库
        user.setStatus(UserStatusConstant.ENABLE);
        user.setRegistDate(new Date());
        userDao.insert(user);
    }

    @Override
    public void modifyPwd(Integer id, String newpassword) {
        userDao.updatePwd(id, newpassword);
    }

    @Override
    public List<User> findAll() {
        return userDao.selectAll();
    }


}
